package com.jyb.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jyb.enumeration.ShanghaiDistrict;
import com.jyb.util.StringUtils;
import com.jyb.util.UUIDUtils;

public class MyOrder extends Model<MyOrder>{

	private static final long serialVersionUID = 4383806186048438586L;
	public static final MyOrder dao = new MyOrder();
	
	public static Map<String,List<Record>> map=new HashMap<String,List<Record>>();
	
	public List<Record> getNewest(Integer limit,String userId){
		if(limit==null){
			limit=10;
		}
		String sql="select * from t_my_order t where t.userId=? order by t.updateTime desc  limit ? ";
		return Db.find(sql,userId,limit);
	}
	
	public Page<Record> pagequery(Integer pageNumber,Integer pageSize,MyOrder myOrder){
		
		if(pageNumber==null){
			pageNumber=1;
		}
		if(pageSize==null){
			pageSize=10;
		}
		
		StringBuffer sqlExceptSelect=new StringBuffer(" from t_my_order t left join iot_building a on a.id=t.buildingId where t.removed='0' ");
		List<Object> list=new ArrayList<Object>();
		
		if(!StringUtils.isEmpty(myOrder.getStr("userId"))){
			sqlExceptSelect.append(" and t.userId=?");
			list.add(myOrder.getStr("userId"));
		}
		
		sqlExceptSelect.append(" order by t.updated desc");
		return Db.paginate(pageNumber,pageSize,"select t.*",sqlExceptSelect.toString(),list.toArray());
	}

	public void updateMyOrder(String userId,String tdh,String cm,String hc){
		String sql="select * from t_my_order t where t.userId=? and t.tdh=?";
		Record record=Db.findFirst(sql,userId,tdh);
		if(record==null){
			sql="insert into t_my_order (id,createTime,updateTime,userId,cm,hc,tdh) values(?,now(),now(),?,?,?,?)";
			Db.update(sql,UUIDUtils.getUUID(),userId,cm,hc,tdh);
		}else{
			sql="update t_my_order t set t.updateTime=now() where t.id=?";
			Db.update(sql,record.getStr("id"));
		}
	}
	
	/**
	 * 跟新码头信息
	 */
	public void updateMyOrderMt(String userId,String tdh,ShanghaiDistrict district){
		if(district==null){
			return;
		}
		String sql="update t_my_order t set t.gk=?,t.gkmc=? where t.userId=? and t.tdh=?";
		Db.update(sql,district.name(),district.getTitle(),userId,tdh);
	}
	
	public List<MyOrder> findNullCm(){
		String sql="select * from t_my_order t where t.tdh is not null and (t.cm is null or t.cm='') and (t.hc is null or t.hc='') and t.createTime>?";
		return this.find(sql,new Date(System.currentTimeMillis()-1000*60*60*24));
	}
	
}
